//
//  NSString+XL.m
//  campus
//
//  Created by xl on 2019/11/27.
//  Copyright © 2019 xl. All rights reserved.
//

#import "NSString+XL.h"
#import <CommonCrypto/CommonDigest.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>
#import <dlfcn.h>
#import <YYText/YYText.h>


@implementation NSString (XL)

+ (NSString *)md5:(NSString *)string {
    NSData* inputData = [string dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char outputData[CC_MD5_DIGEST_LENGTH];
    CC_MD5([inputData bytes], (unsigned int)[inputData length], outputData);
    
    NSMutableString* hashStr = [NSMutableString string];
    int i = 0;
    for (i = 0; i < CC_MD5_DIGEST_LENGTH; ++i)
        [hashStr appendFormat:@"%02x", outputData[i]];
    
    return hashStr;
}

/** 移除文本两端的空格和换行符 **/
+ (NSString *)removeTextBothEndsSpaceAndNewline:(NSString *)text {
    if (ISEmptyString(text)) {
        return text;
    }
    NSString *temp = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *newText = [temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];
    return newText;
}

/** data转化16进制的string **/
+ (NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}

/** 根据设备类型获取设备名 **/
+ (NSString *)deviceName:(NSInteger)deviceType {
//    if (deviceType == XLDeviceTypeWaterHeater) {
//        return XLWaterHeaterText;
//    }
//    else if (deviceType == XLDeviceTypeDrinkingFountain)
//    {
//        return XLDrinkingFountainText;
//    }
//    else if (deviceType == XLDeviceTypeBlower)
//    {
//        return XLBlowerText;
//    }
//    else if (deviceType == XLDeviceTypeWashingMachine)
//    {
//        return XLWashingMachineText;
//    }
//    else if (deviceType == XLDeviceTypePublicBath)
//    {
//        return XLWaterHeaterText;
//    }
//    else if (deviceType == XLDeviceTypeDryerMachine)
//    {
//        return XLDryerMachineText;
//    }
//    else if (deviceType == XLDeviceTypeWashShoeMachine)
//    {
//        return XLWashShoesMachineText;
//    }
    return @"未知";
}

/** 验证手机数字(0123456789) **/
- (BOOL)validatePhoneNumber {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < self.length) {
        NSString * string = [self substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

/** 验证钱数字（0123456789.） **/
- (BOOL)validateMoneyNumber {
    BOOL res = YES;
       NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
       int i = 0;
       while (i < self.length) {
           NSString * string = [self substringWithRange:NSMakeRange(i, 1)];
           NSRange range = [string rangeOfCharacterFromSet:tmpSet];
           if (range.length == 0) {
               res = NO;
               break;
           }
           i++;
       }
       return res;
}

/** 判断中英混合的的字符串长度 **/
- (int)convertToInt:(NSString *)strTemp {
    int strlength = 0;
    for (int i=0; i< [strTemp length]; i++) {
        int a = [strTemp characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff) { //判断是否为中文
            strlength += 2;
        }
    }
    return strlength;
}

/** 二维码图片识别 **/
+ (NSString *)scanQRCodeImage:(UIImage *)image {
    if (image.size.width < 10) {
            return nil;
        }
    NSArray *filterNames = [CIFilter filterNamesInCategory:kCICategorySharpen];
    NSLog(@"filterNames:%@",filterNames);
    CIImage *outPutImage = [CIImage imageWithCGImage:image.CGImage];

    CIFilter *filter = [CIFilter filterWithName:@"CIUnsharpMask" keysAndValues:kCIInputImageKey,outPutImage,kCIInputIntensityKey,@(2), nil];
    CIContext *context = [CIContext contextWithOptions:nil];
    //    CIContext *context = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer:@(YES)}]; // 软件渲染
    CGImageRef resultImage = [context createCGImage:filter.outputImage fromRect:filter.outputImage.extent];
        
    UIImage *tipImage = [UIImage imageWithCGImage:resultImage];
    NSLog(@"%f",tipImage.size.height);
    CIDetector*detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
    NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:resultImage]];
    CGImageRelease(resultImage);
    NSString *code = nil;
    for (CIQRCodeFeature *feature in features) {
        code = feature.messageString;
        if (code != nil) {
            break;
        }
    }
    return code;
}

/** 二维码图片识别 **/
+ (NSString *)scanQRCodeImageWithCIImage:(CIImage *)image {
    CIContext *context = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer:@(YES)}]; // 软件渲染
    CIDetector*detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
    NSArray *features = [detector featuresInImage:image];
    NSString *code = nil;
    for (CIQRCodeFeature *feature in features) {
        code = feature.messageString;
        if (code != nil) {
            break;
        }
    }
    return code;
}

/** 转换视频时间显示 totalSeconds 时间总长 **/
+ (NSString *)videoTimeFormatted:(int)totalSeconds {
    if (totalSeconds == 0) {
        return @"0:00";
    }
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    if (hours == 0) {
        return [NSString stringWithFormat:@"%01d:%02d", minutes, seconds];
    }
    return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
}

/** 隐藏手机号中间四位，用*代替 **/
+ (NSString *)safePhoneNumber:(NSNumber *)number {
    if (number.stringValue.length == 11) {
        NSString *str = [number.stringValue stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        return str;
    }
    return number.stringValue;
}

- (CGFloat)calculateRowHeightWithFont:(UIFont *)font width:(CGFloat)width {
    NSDictionary *dic = @{NSFontAttributeName:font};
    CGRect rect = [self boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
    return rect.size.height;
}

- (CGFloat)calculateRowWidthWithFont:(UIFont *)font height:(CGFloat)height {
    NSDictionary *dic = @{NSFontAttributeName:font};
    CGRect rect = [self boundingRectWithSize:CGSizeMake(MAXFLOAT, height) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
    return rect.size.width;
}

- (CGFloat)calculateRowYYLabelWidthWithAttri:(NSAttributedString *)attri
                                      height:(CGFloat)height {
    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:CGSizeMake(MAXFLOAT, height) text:attri];
    return layout.textBoundingSize.width;
}

- (BOOL)isJudgePassWordLegal{
    // 验证密码长度
    if(self.length < 6 || self.length > 20) {
        return NO;
    }
    // 验证密码是否包含数字
    NSString *numPattern = @".*\\d+.*";
    NSPredicate *numPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numPattern];
    if (![numPred evaluateWithObject:self]) {
        return NO;
    }
    
    // 验证密码是否包含小写字母
    NSString *lowerPattern = @".*[a-z]+.*";
    NSPredicate *lowerPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", lowerPattern];
    if (![lowerPred evaluateWithObject:self]) {
        return NO;
    }
    
    // 验证密码是否包含大写字母
    NSString *upperPattern = @".*[A-Z]+.*";
    NSPredicate *upperPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", upperPattern];
    if (![upperPred evaluateWithObject:self]) {
        return NO;
    }
    return YES;
}

/** 获取当前网络IP地址 **/
+ (NSString *)fetchCurrentNetIP {
    BOOL success;
    struct ifaddrs * addrs;
    const struct ifaddrs * cursor;
    success = getifaddrs(&addrs) == 0;
    if (success) {
    cursor = addrs;
    while (cursor != NULL) {
    // the second test keeps from picking up the loopback address
    if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
    {
    NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
    if ([name isEqualToString:@"en0"]) // Wi-Fi adapter
    NSLog(@"IP:%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)]);
    return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
    }
    cursor = cursor->ifa_next;
    }
    freeifaddrs(addrs);
    }
    return nil;
}

- (unsigned long long)fileSize
{
    // 总大小
    unsigned long long size = 0;
    NSString *sizeText = nil;
    NSFileManager *manager = [NSFileManager defaultManager];
 
    BOOL isDir = NO;
    BOOL exist = [manager fileExistsAtPath:self isDirectory:&isDir];
 
    // 判断路径是否存在
    if (!exist) return size;
    if (isDir) { // 是文件夹
        NSDirectoryEnumerator *enumerator = [manager enumeratorAtPath:self];
        for (NSString *subPath in enumerator) {
            NSString *fullPath = [self stringByAppendingPathComponent:subPath];
            size += [manager attributesOfItemAtPath:fullPath error:nil].fileSize;
 
            }
        }else{ // 是文件
            size += [manager attributesOfItemAtPath:self error:nil].fileSize;
        }
        return size;
}

@end
